<?php

$this->useClass("Handler_Community");
class Action_Community_LeaveCommunity extends Handler_Community
{
	private function getCommunityUsers() {
		$this->rh->UseClass("AggregatedModel_Feed_FeedInterface");
		$this->rh->UseClass("AggregatedModel_Feed_ReaderUsers");

		$model = new AggregatedModel_Feed_ReaderUsers();
		$model->rh = $this->rh;
		$model->setModelParams( 'community_oid', $this->acl_data['comity_oid'] );
		$model->doStuff();
		return $model->getItems();
	}

	private function getModeratorOID( $roles ) {
		foreach ( $roles as $role ) {
			if ( 'moderator' == $role['name'] ) {
				return $role['oid'];
			}
		}

		return 0;
	}

	private function getRoles() {
		$roles_ql = 'select objects where role.oid == 9 OR role.oid == 12'; // показываем только часть ролей #196
		$rs = $this->ctx->store->find($roles_ql);
		if ($rs) {
			$roles = array();
			while ($role = $rs->next()) {
				$t = $role->data;
				$t['oid'] = $role->id;
				$roles[$role->id] = $t;
			}
		}
		return $roles;
	}

	private function getModeratorsCount($users, $moderator_oid) {
		$count = 0;
		foreach ( $users as $user ) {
			if( $moderator_oid == $user['role_oid'] ) {
				$count++;
			}
		}
		return $count;
	}

	public function process ()
	{
		if (isset($_POST['ok_x'])) {
			$acl_assistant = $this->aa;
			$acl_data = $this->acl_data;

			$community_oid = $this->acl_data['comity_oid'];
			$users = $this->getCommunityUsers();

			if ( 'moderator' == $acl_data['role']['name'] ) {
				$roles = $this->getRoles();
				$moderator_oid = $this->getModeratorOID($roles);

				$moderatorsCount = $this->getModeratorsCount($users, $moderator_oid);
				if ( $moderatorsCount < 2 ) {
					$model = $this->ctx->mm->getModel("User", "m");
					foreach ( $users as $user ) {
						$model->setRoleByOid($community_oid, $user['oid'], $moderator_oid);
					}
				}
			}

			if ( 1 == count($users) ) {
				$model = $this->ctx->mm->getModel("Community", "m");
				$config = $model->getConfig($community_oid);

				if ('moderated' == $config['join_mode']) {
					$config['join_mode'] = 'free';
					$model->saveConfig($community_oid, $config);
				}
			}

			if ($acl_data['user']['user_id']) {
				$community_oid = $acl_data['comity_oid'];
				$user_id = $acl_data['user']['user_id'];
				$this->ctx->db->begin();
				$this->leaveCommunity($community_oid, $user_id);
				$this->ctx->db->end();
			}

			$this->rh->UseClass('RL_URLGenerator');
			$ug = new RL_URLGenerator($this->rh->router->getRule('community'));
			$ug->setRouter($this->rh->router);
			$ug->setParams($this->params);
			$url = $ug->generateUrl();
			$this->rh->redirect($url);
		}
	} // end of function process

}

